package it.unical.canonaco.rende.igpe.game.cbv.logiclayer.engine.component.pawn;

import java.util.Collection;
import java.util.TreeMap;
import java.util.TreeSet;

public class Inventory {

	/** List of items in the inventory **/
	private static final int MAX_ITEM_SLOTS = 8;
	private TreeMap<Integer, String> inventoryItems = new TreeMap<Integer, String>();
	private TreeSet<Integer> freeSlots = new TreeSet<Integer>();
	
	public Inventory() {
		
		for(int i = 0; i<MAX_ITEM_SLOTS; i++)
			freeSlots.add(i);
		
	}
	
	public boolean isFull(){
		return freeSlots.size() == 0;
	}
	
	public String removeItem(int index){
		
		if(!hasItem(index))
			return null;
		
		// add new slot to freeSlots available (must be ordered hence treeSet)
		freeSlots.add(index);
		return inventoryItems.remove(index);
	}
	
	public boolean addItem(String itemName){
		
		// if there are no free slots, the item cannot be added to the inventory
		if(freeSlots.size() == 0)
			return false;
		
		// retrieve the first available slot for the item to be added
		// and remove the index from the available slots (since now it's occupied)
		Integer firstAvailableSlot = freeSlots.pollFirst();
		// put the item in the free slot
		inventoryItems.put(firstAvailableSlot, itemName);
		return true;

		
	}
	
	public boolean addItemByIndex(int index, String itemName){
	// if index position is not available, it means it's already occupied by another item
		if(!freeSlots.contains(index))
			return false;
		
		inventoryItems.put(index, itemName);
		freeSlots.remove(index);
		
		return true;
		
	}
	
	public boolean hasItem(int index){
		return inventoryItems.containsKey(index);
	}

	/**
	 * 
	 * @param index
	 * @return the item name specified by index location, otherwise null value.
	 */
	public String getItem(int index){
		
		return inventoryItems.get(index);
	}
	
	public Collection<String> getItemNames(){
		
		return inventoryItems.values();
	}

	public boolean isSlotFree(int index) {
		
		return freeSlots.contains(index);
	}
	
}